package lzq.aop.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import lzq.aop.config.DataSourceUtils;
import lzq.aop.config.JdbcTemplate;

@Aspect
@Component
public class MyAspect {

	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	public MyAspect() {
		System.out.println("MyAspect created ");
	}
	
	
	@Around("execution(* lzq.aop.service.*.create*(..)) "
			+ "|| execution(* lzq.aop.service.*.delete*(..))"
			+ " || execution(* lzq.aop.service.*.update*(..))")
	public void beginTransaction(ProceedingJoinPoint pjp ) {
		
		System.out.println("当前要执行方法"+pjp.getSignature()+",使用事务.");
		DataSourceUtils.startTransaction(jdbcTemplate.getDataSource());
		try {
			pjp.proceed();
			DataSourceUtils.commit();
			System.out.println("正常执行，提交事务");
			
		} catch (Throwable e) {
			System.out.println("执行方法出现异常，回滚");
			DataSourceUtils.rollback();
			e.printStackTrace();
		}finally {
			DataSourceUtils.close();
		}
		
	}

	
	@Before("execution(* lzq.aop.service.*.query*(..))")
	public void withoutTransaction(JoinPoint jp ) {
		System.out.println("当前要执行方法"+jp.getSignature()+",不使用事务.");
		DataSourceUtils.getConnection(jdbcTemplate.getDataSource());
		
	}
	
}
